package com.leha.mp.core.Utils;

import com.google.common.io.Closer;
import com.leha.utils.DateTool;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.apache.commons.io.IOUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

public class COSUtil {
    private static  String accessKey = ResourceBundle.getBundle("common").getString("cos.accessKey");
    private static  String secretKey = ResourceBundle.getBundle("common").getString("cos.secretKey");
    private static String region= ResourceBundle.getBundle("common").getString("cos.region");
    private static String bucketName= ResourceBundle.getBundle("common").getString("cos.bucketName");
    private static String RES_ULR= ResourceBundle.getBundle("common").getString("cos.RES_ULR");

    private static Map<String, String> miniType = new HashMap<String,String>();
    static {
        miniType.put("txt", "text/plain");
        miniType.put("html", "text/html");
        miniType.put("xml", "application/xml");
        miniType.put("gif", "image/gif");
        miniType.put("jpg", "image/jpeg");
        miniType.put("jpeg", "image/jpeg");
        miniType.put("png", "image/png");
        miniType.put("mpeg", "video/mpeg");
        miniType.put("pdf", "application/pdf");
        miniType.put("doc", "application/msword");
        miniType.put("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        miniType.put("xls", "application/vnd.ms-excel");
        miniType.put("xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        miniType.put("ppt", "application/vnd.ms-powerpoint");
        miniType.put("pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation");
        miniType.put("", "image/png");
    }

    public static String getSuffixByFilename(String filename) {
        String extName = "";
        if (filename != null) {
            if ((filename != null) && (filename.indexOf(".") != -1)) {
                extName = filename.substring(filename.lastIndexOf(".") + 1);
            }
        }
        return extName.toLowerCase();
    }

    public static FileInfo putFile(MultipartFile avatarFile) {
        String suffix = COSUtil.getSuffixByFilename(avatarFile.getOriginalFilename());
        try {
            return COSUtil.putFile(avatarFile.getInputStream(), suffix);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("upload file error", e);
        }
    }



    public static String getMineType(String suffix) {
        if (miniType.containsKey(suffix)) {
            return miniType.get(suffix);
        } else {
            return "application/octet-stream";
        }
    }

    public static FileInfo putFile(InputStream inputStream, String suffix) {
        // 1 初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials(accessKey, secretKey);
        // 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        // 3 生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);
        // bucket的命名规则为{name}-{appid} ，此处填写的存储桶名称必须为此格式

        String miniType = getMineType(suffix);
        // 创建上传Object的Metadata
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentType(miniType);
        // 必须设置ContentLength
        try {
            meta.setContentLength(inputStream.available());
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileInfo fileInfo = new FileInfo();
        Closer closer = Closer.create();

        ByteArrayOutputStream buffer = closer.register(new ByteArrayOutputStream());
        try {
            IOUtils.copy(inputStream , buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String realPath = DateTool.getNow("yyyyMMdd") + "/" + UUID.randomUUID().toString().replaceAll("-", "");
        if (StringUtils.hasText(suffix)) {
            realPath += "." + suffix;
        }
        try {
            // 上传Object.
            PutObjectResult result = cosclient.putObject(bucketName, realPath, closer.register(new ByteArrayInputStream(buffer.toByteArray())), meta);
            // 打印ETag
            System.out.println(result.getETag());
            fileInfo.setUrl(RES_ULR + "/" + realPath);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (suffix.equalsIgnoreCase("jpg") || suffix.equalsIgnoreCase("jpeg") || suffix.equalsIgnoreCase("gif")
                || suffix.equalsIgnoreCase("bmp") || suffix.equalsIgnoreCase("png")) {

            try {
                ImageInputStream iis = ImageIO.createImageInputStream(closer.register(new ByteArrayInputStream(buffer.toByteArray())));
                Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);

                if (readers.hasNext()) {
                    //Get the first available ImageReader
                    ImageReader reader = readers.next();
                    reader.setInput(iis, true);

                    fileInfo.setH(reader.getHeight(0));
                    fileInfo.setW(reader.getWidth(0));
                }

                iis.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
            }
        }

        try {
            closer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileInfo;
    }
}
